package com.sky.task;


import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单，将超过15分钟未支付的全部处理为已取消
     */
    @Scheduled(cron = "0 * * * * ?")    //每分钟触发一次
    //@Scheduled(cron = "1/5 * * * * ?")  //测试用
    public void processTimeOutOrder(){
        log.info("处理超时订单：{}", LocalDateTime.now());

        Integer status = Orders.PENDING_PAYMENT;   //这是未支付的订单状态
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);  //这是15分钟前的时间

        //获取超时订单集进行统一处理
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(status, time);

        if (ordersList.size() > 0 && ordersList != null){
            for (Orders orders : ordersList) {
                //修改订单信息，为已取消的订单信息状态
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消");
                orders.setStatus(Orders.CANCELLED);
                orderMapper.update(orders);
            }
        }
    }


    /**
     * 处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")  //测试用
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());

        Integer status = Orders.DELIVERY_IN_PROGRESS;   //这是派送中的订单状态
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);   //这是处理时的系统时间，即上一个工作日的时间

        //对仍在派送中的订单进行统一处理
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(status, time);

        if (ordersList.size() > 0 && ordersList != null){
            for (Orders orders : ordersList) {
                //修改订单信息，为已取消的订单信息状态
                orders.setDeliveryTime(LocalDateTime.now());
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
